import { PLAY_MODE } from '@/assets/js/constant'
import { shuffle } from '@/assets/js/util'

export function selectPlay ({ commit, state }, { list, index }) {
  commit('setPlayMode', PLAY_MODE.sequence)
  commit('setSequenceList', list)
  commit('setPlayingState', true)
  commit('setFullScreen', true)
  commit('setPlaylist', list)
  commit('setCurrentIndex', index)
}
export function randomPlay ({ commit }, { list }) {
  commit('setPlayMode', PLAY_MODE.random)
  commit('setSequenceList', list)
  commit('setPlayingState', true)
  commit('setFullScreen', true)
  commit('setPlaylist', shuffle(list))
  // 播放第一首
  commit('setCurrentIndex', 0)
}
// 切换播放模式
export function changeMode ({ commit, state, getters }, mode) {
  // 改变播放模式，但不切当前播放歌曲
  const currentId = getters.currentSong.id
  if (mode === PLAY_MODE.random) {
    commit('setPlaylist', shuffle(state.sequenceList))
  } else {
    commit('setPlaylist', state.sequenceList)
  }

  // 歌手歌曲列表点进来的索引
  const index = state.playlist.findIndex((song) => song.id === currentId)
  commit('setCurrentIndex', index)
  commit('setPlayMode', mode)
}
export function removeSong ({ commit, state }, song) {
  const sequenceList = state.sequenceList.slice()
  const playlist = state.playlist.slice()
  // 索引
  const sequenceIndex = findIndex(sequenceList, song)
  const playlistIndex = findIndex(playlist, song)
  sequenceList.splice(sequenceIndex, 1)
  playlist.splice(playlistIndex, 1)
  commit('setSequenceList', sequenceList)
  commit('setPlaylist', playlist)
}
function findIndex (list, song) {
  return list.findIndex((item) => item.id === song.id)
}
